<template>
	<!-- 表单弹窗 -->
	<el-dialog 
		v-model="dialogFormVisible" 
		:title="formText"
		 class="elDiaLog"
		lock-scroll width="1000px" :close-on-click-modal="false" :close-on-press-escape="false">
		
		<div class="form-box" v-loading="loading" v-if="['act_info'].includes(dialogStatus)">
			<el-descriptions size="default" :column="1" border>
				
				<el-descriptions-item label-class-name="labelC1"
					label="项目名称：">{{formTemp.name}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" label="所属公司：">{{formTemp.company}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="贷款主体：">{{formTemp.subject}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="机构名称：">{{formTemp.agency}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="贷款年限：">{{formTemp.year}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="贷款起始日：">{{formTemp.start_date}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="贷款终止日：">{{formTemp.end_date}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="距现到期时间：">
					<el-text type="danger">{{daysBetweenDates(formTemp.start_date,formTemp.end_date)}}</el-text>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" label="年利率：">{{formTemp.rate}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="担保方式：">{{formTemp.danbao}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="协议金额：">{{formTemp.money}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="余额：">
					<el-text type="danger">{{formTemp.balance}}</el-text></el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" label="是否隐形债务：">
					{{formTemp.is_implicit==1?'是':'否'}}
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="付息方式：">
					{{formTemp.interest_type}}
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" label="附件：">
					<div v-if="formTemp.files?.length >0" v-for="(ite,ind) in formTemp.files" >
						<el-link @click="onFilePreview(ite)" type="primary">{{ind + 1}}.{{ite.name}}</el-link>
					</div> 
					 <el-link v-else type="info">无</el-link>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="添加人：">
					<span>{{formTemp.user?.name}}</span>	
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="添加时间：">
				{{formTemp.add_time_text}}
				</el-descriptions-item>
			</el-descriptions>
		</div>
		<div class="form-box" v-if="['act_add','act_edit'].includes(dialogStatus)">
			<el-form ref="dataFormRef" :model="formTemp" :rules="formRules" label-width="150px">
				<el-form-item required label="项目名称" prop="name">
					<el-input placeholder="请输入项目名称" v-model="formTemp.name" />
				</el-form-item>
				<el-form-item required label="所属公司" prop="cid">
					<el-tree-select v-model="formTemp.cid" 
					:data="baseConfigStore.newExCompanyList"
					check-strictly
					:render-after-expand="false" 
					style="width: 100%" 
					placeholder="请选择所属公司" >
					<template v-slot:default="{node, data }">
							<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
						</template>
					</el-tree-select>	
				</el-form-item>
				<el-form-item required label="贷款主体" prop="subject">
					<el-input placeholder="请输入贷款主体" v-model="formTemp.subject" />
				</el-form-item>
				<el-form-item required label="机构名称" prop="agency">
					<el-input placeholder="请输入机构名称" v-model="formTemp.agency" />
				</el-form-item>
				<el-form-item label="贷款年限" prop="year">
					<el-input placeholder="请输入贷款年限" v-model="formTemp.year" />
				</el-form-item>
				<el-form-item label="贷款起始日" prop="start_date">
					<el-date-picker v-model="formTemp.start_date" type="date" format="YYYY-MM-DD"
						value-format="YYYY-MM-DD" placeholder="请选择贷款起始日" />
				</el-form-item>
				<el-form-item label="贷款终止日" prop="end_date">
					<el-date-picker v-model="formTemp.end_date" type="date" format="YYYY-MM-DD"
						value-format="YYYY-MM-DD" placeholder="请选择贷款起始日" />
				</el-form-item>
				<el-form-item label="距现到期时间" prop="juxiandaoqiriqi">
					<el-text type="danger">{{daysBetweenDates(formTemp.start_date,formTemp.end_date)}}</el-text>
				</el-form-item>
				<el-form-item label="年利率" prop="rate">
					<el-input placeholder="请输入年利率" v-model="formTemp.rate" />
				</el-form-item>
				<el-form-item label="担保方式" prop="danbao">
					<el-input placeholder="请输入担保方式" v-model="formTemp.danbao" />
				</el-form-item>
				<el-form-item label="协议金额" prop="money">
					<el-input placeholder="请输入协议金额" v-model="formTemp.money" 	>
					 <template #append>元</template>
					 </el-input>
				</el-form-item>
			
				<el-form-item label="是否隐形债务" prop="is_implicit">
					<el-radio-group v-model="formTemp.is_implicit">
						<el-radio :value="0" size="large">否</el-radio>
						<el-radio :value="1" size="large">是</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="付息方式" prop="interest_type">
					<el-input placeholder="请输入付息方式" v-model="formTemp.interest_type" />
				</el-form-item>
				<el-form-item label="附件上传" prop="files">
					<el-upload class="allwidth" name="file" v-model:file-list="formTemp.files" action="/api/upload"
						:data="{type:'file'}" show-file-list :auto-upload="true" :multiple="true"
						:on-success="(response:any, file:any, fileList:any) => {return imageBeforUploadSuccess(response, file, fileList,'files');}"
						:on-preview="onFilePreview" :before-upload="imageBeforUpload" :limit="10">
						<el-button type="primary"><template #icon><i-ep-UploadFilled /></template>上传文件</el-button>
						<template #tip>
							<div class="el-upload__tip">
								<el-text size="small" type="info">{{feilType.pageShow}}</el-text>
							</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
		</div>

		<template #footer>
			<div class="dialog-footer">
				<el-button v-if="['act_info'].includes(dialogStatus)"  @click="dialogFormVisible = false">关 闭</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" @click="doData(dialogStatus)" type="primary" v-no-more-click >确 定</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" @click="dialogFormVisible = false">取 消</el-button>
			</div>
		</template>
	</el-dialog>
</template>


<script setup lang="ts">
	import { useRoute } from 'vue-router';
	import _ from 'lodash-es'
	import { feilType, daysBetweenDates, onFilePreview } from "@/utils/funcall"
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();

	// 获取接口地址
	import {
		addFinancing,
		updataFinancing,
		getFinancing,
		deleteFinancing
	} from "@/api/financing";
	
	// 表单模型
	const cForm = {
		id:undefined,
		name:"",//项目名称
		cid:"",//所属公司
		subject:"",//贷款主体
		agency:"",//机构名称
		year:"",//贷款年限
		start_date:"",//贷款起始日期
		end_date:"",//贷款终止日期
		rate:"",//年利率
		danbao:"",// 担保方式
		money:"",//协议金额
		is_implicit:"",//是否隐性债务
		interest_type:"",//付息方式
		files:[]//文件上传
	}
	// 验证规则
	const cRules = {
		name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
		cid: [{ required: true, message: '请输入所属公司', trigger: 'blur' }],
		subject: [{ required: true, message: '请输入贷款主体', trigger: 'blur' }],
		agency: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
		year: [{ required: true, message: '请输入贷款年限', trigger: 'blur' }],
		start_date: [{ required: true, message: '请选择贷款起始日期', trigger: 'blur' }],
		end_date: [{ required: true, message: '请选择贷款终止日期', trigger: 'blur' }],
		rate: [{ required: true, message: '请输入年利率', trigger: 'blur' }],
		danbao: [{ required: true, message: '请输入担保方式', trigger: 'blur' }],
		money: [{ required: true, message: '请输入协议金额', trigger: 'blur' }],
		is_implicit: [{ required: true, message: '请选择是否隐性债务', trigger: 'blur' }],
		interest_type: [{ required: true, message: '请输入付息方式', trigger: 'blur' }],
	}
	const emit = defineEmits(['initRefreshList']);
	const dialogFormVisible = ref(false);
	const loading = ref(false);//新增或者修改加载load按钮
	// 数据的data-ref
	const dataFormRef = ref(ElForm);
	const dialogStatus = ref<string>(""); // 操作行为 formText
	const formText =ref<string>(""); // 操作窗口标题
	const formTemp = ref<any>(cForm);
	//验证规则
	const formRules = ref<any>(cRules);
	// 初始表单数据
	function resetTemp() {
		formTemp.value = JSON.parse(JSON.stringify(cForm));
		resetForm();
	}
	// 表单重置
	function resetForm() {
		dataFormRef.value.resetFields()
	}
	//新增或者修改加载load按钮
	function handleShow(row:any, act:string){
		handleDo(row,act)
	}
	// 操作
	 function handleDo(row:any, act:string) {
		dialogStatus.value = act
		switch (act) {
			case 'act_add':	
				dialogFormVisible.value = true;
				formText.value = '新建信息'
				formTemp.value = JSON.parse(JSON.stringify(cForm))
				formRules.value = Object.assign({}, cRules)
				nextTick(()=>{
					setTimeout(()=>{dataFormRef.value.clearValidate();},100)
				})
				break
			case 'act_edit':
				dialogFormVisible.value = true;
				formText.value = '修改信息';
				formTemp.value = JSON.parse(JSON.stringify(row));
				nextTick(()=>{
					setTimeout(()=>{dataFormRef.value.clearValidate();},0)
				})
				break
			case 'act_del':
				handleDelete(JSON.parse(JSON.stringify(row)))
				break
			default:
				dialogFormVisible.value = true;
				formText.value = '查看详情'
				formTemp.value = JSON.parse(JSON.stringify(row))
				getFinancing({ id: formTemp.value.id }).then((res:any) => {
					formTemp.value = res.data;
				}).finally(() => {
					 loading.value = false;
				})
		}
	}
	
	// 提交数据
	function doData(act:string) {
		dataFormRef.value.validate((valid:any) => {
			if (valid) {
				loading.value = true;
				const tempData = JSON.parse(JSON.stringify(formTemp.value))
				if (tempData.id == undefined) {
					addFinancing(tempData).then((res) => {
						dialogFormVisible.value = false
						ElMessage({ message:'信息添加成功',type:'success'})
						emit('initRefreshList');
					}).finally(() => {
						loading.value = false;
					})
				 } 
				 else {
					updataFinancing(tempData).then((res) => {
						dialogFormVisible.value = false
						ElMessage({ message:'信息修改成功',type:'success'})
						emit('initRefreshList');
					}).finally(() => {
						loading.value = false;
					})
				}
			}
		})
	}
	
	// 删除表单内容
	function handleDelete(row:any) {
		const Ids =row.id;
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			loading.value = true;
			deleteFinancing({ id: Ids }).then(() => {
				ElMessage.success("删除成功");
				emit('initRefreshList');
			}).finally(() => (loading.value = false));
		});
	}
	/**
	 * 上传文件 之前的操作
	 */
	function imageBeforUpload(file : any) {
		var fileSize = file.size / 1024 / 1024 < feilType.size;
		const index = file.name.lastIndexOf(".");
		const ext = file.name.substr(index + 1).toUpperCase();
		if (feilType.extarr.indexOf(ext) == -1) {
			ElMessage({
				message: feilType.errorMes,
				type: 'error',
			})
			return false;
		}
		if (!fileSize) {
			ElMessage({
				message: feilType.prompt,
				type: 'error',
			})
			return false;
		}
	}
	// 图片和文件类型上传成功之后的回调
	function imageBeforUploadSuccess(response : any, file : any, fileList : any, el : any) {
		formTemp.value[el] = formTemp.value[el].map(item => {
			if (item.uid == file.uid) {
				const obj : any = {}
				obj.uid = file.uid
				obj.url = response.data.url
				obj.name = file.name
				return obj;
			}
			else {
				return item;
			}
		});
	}
	onMounted(() => {});
	defineExpose({
	  handleShow
	});
</script>

